import json

from flask import g

from common.libs import Helper
from common.libs.UrlManager import UrlManager
from common.models.members.Member import Member
from common.models.members.MemberCart import MemberCart
from web.controllers.api import api_route, request, Restful, Food
from common.libs.CartService.CartService import CartService


@api_route.route('/cart/set/', methods=['POST'])
def cartSet():
    resp = request.values
    food_id = int(resp['id']) if 'id' in resp else 0
    number = int(resp['number']) if 'number' in resp else 0
    if food_id < 1 or number < 1:
        return Restful.param_error('参数错误！')

    food_info = Food.query.filter_by(id=food_id).first()
    if not food_info:
        return Restful.notfound_error()
    if food_info.stock < number:
        return Restful.format_error(msg='库存不足')
    member_info = g.member_info
    member_cart = CartService()
    if not member_cart.setItems(food_id=food_id, member_id=member_info.id, number=number):
        return Restful.format_error('加入购物车失败')
    return Restful.success()


@api_route.route('/cart/delete/', methods=['POST'])
def cartDelete():
    resp = request.values
    food_ids = json.loads(resp['food_ids']) if 'food_ids' in resp else []
    if not food_ids:
        return Restful.format_error(msg='没有要删除的商品！')
    member_info = g.member_info
    if not member_info:
        return Restful.token_expri_error()
    member_cart = CartService()
    if not member_cart.deleteItem(member_id=member_info.id, items=food_ids):
        return Restful.format_error('商品删除失败')
    data_cart_list = member_cart.cartList(member_id=member_info.id)
    return Restful.success(data={'list': data_cart_list})


@api_route.route('/cart/list/', methods=['POST'])
def cartList():
    member = g.member_info
    if not member:
        return Restful.format_error(msg='未找到此用户')
    member_cart = CartService()
    data_cart_list = member_cart.cartList(member_id=member.id)
    return Restful.success(data={'list': data_cart_list})















